<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>天文数据查询与可视化</title>
    <!-- Three.js 依赖 -->
    <script
      async
      src="https://unpkg.com/es-module-shims@1.8.0/dist/es-module-shims.js"
    ></script>
    <script type="importmap">
      {
        "imports": {
          "three": "https://unpkg.com/three@0.156.1/build/three.module.js",
          "three/addons/": "https://unpkg.com/three@0.156.1/examples/jsm/"
        }
      }
    </script>
    <style>
      body {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
        background-color: #1c023f;
        color: white;
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        overflow-x: hidden;
      }

      * {
        box-sizing: border-box;
      }

      canvas {
        display: block;
      }

      #info {
        position: absolute;
        top: 10px;
        left: 10px;
        color: yellow;
        font-family: monospace;
        font-size: 14px;
        white-space: pre;
        text-shadow: 1px 1px 1px black;
        background: rgba(0, 0, 0, 0.7);
        padding: 0.8rem 1rem;
        border-radius: 6px;
        backdrop-filter: blur(4px);
        z-index: 1000;
      }

      .label {
        color: #ffffff;
        font-family: sans-serif;
        padding: 2px;
        background: rgba(0, 0, 0, 0.6);
      }

      .header,
      .footer,
      .search-container {
        max-width: 100%;
        box-sizing: border-box;
      }

      .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 80px;
        background-color: #1c023f;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 20px;
        margin-top: auto;
        z-index: 1000;
      }

      .button {
        background: rgba(107, 85, 180, 0.7);
        opacity: 0.6;
        border: none;
        border-radius: 10px;
        color: white;
        padding: 12px;
        text-align: center;
        margin: 10px;
        cursor: pointer;
        transition: background-color 0.3s;
        width: 30px;
        /* 设置按钮的固定宽度 */
        height: 100px;
        /* 设置按钮的固定高度 */
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .button:hover {
        background: #5b4aa3;
      }

      .footer svg {
        color: white;
        font-size: 24px;
      }

      .back-btn,
      .location-btn,
      .calendar-btn,
      .moon-btn,
      .data-btn,
      .index-btn {
        margin-right: 10px;
        background: none;
        border: none;
        padding: 0;
        cursor: pointer;
        transition: opacity 0.3s;
      }

      .back-btn:hover,
      .location-btn:hover,
      .calendar-btn:hover,
      .moon-btn:hover,
      .data-btn:hover,
      .index-btn:hover {
        opacity: 0.8;
      }

      .container {
        display: grid;
        grid-template-columns: minmax(280px, 320px) 1fr;
        min-height: 100vh;
      }

      .input-panel {
        background: rgba(0, 0, 0, 0.6);
        padding: 2rem;
        border-right: 1px solid #333;
        box-shadow: 2px 0 5px rgba(0, 0, 0, 0.3);
        overflow-y: auto;
        height: 100vh;
      }

      .input-panel h2 {
        margin-bottom: 1.5rem;
        color: white;
        font-size: 1.5rem;
      }

      .form-group {
        margin-bottom: 1.2rem;
      }

      label {
        display: block;
        margin-bottom: 0.5rem;
        color: white;
        font-weight: 500;
      }

      input {
        width: 100%;
        padding: 0.8rem;
        border: 1px solid #444;
        border-radius: 6px;
        font-size: 1rem;
        background: rgba(255, 255, 255, 0.9);
        transition: border-color 0.3s, box-shadow 0.3s;
      }

      input:focus {
        outline: none;
        border-color: #6b55b4;
        box-shadow: 0 0 0 3px rgba(107, 85, 180, 0.2);
      }

      button[type="submit"] {
        width: 100%;
        background: rgba(107, 85, 180, 0.7);
        color: white;
        padding: 1rem;
        border: none;
        border-radius: 6px;
        font-size: 1rem;
        font-weight: 500;
        cursor: pointer;
        transition: background-color 0.3s;
        height: auto;
      }

      button[type="submit"]:hover {
        background: #5b4aa3;
      }

      #result {
        margin-top: 1.5rem;
        padding: 1rem;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 6px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        color: white;
      }

      #result p {
        margin-bottom: 0.5rem;
        font-size: 0.95rem;
      }

      .visualization-panel {
        position: relative;
        background: #000;
        overflow: hidden;
      }

      #threeCanvas {
        width: 100%;
        height: 100%;
        display: block;
      }

      .orientation-label {
        color: #ffffff;
        font-family: sans-serif;
        padding: 2px;
        background: rgba(0, 0, 0, 0.6);
      }

      @media (max-width: 768px) {
        .container {
          grid-template-columns: 1fr;
          grid-template-rows: auto 1fr;
        }

        .input-panel {
          height: auto;
          min-height: unset;
          border-right: none;
          border-bottom: 1px solid #333;
          padding: 1.5rem;
        }

        .visualization-panel {
          height: 60vh;
        }
      }
    </style>
  </head>

  <body>
    <div class="container">
      <div class="input-panel">
        <h2>天文数据查询</h2>
        <form id="astroForm">
          <div class="form-group">
            <label for="latitude">纬度 (Latitude)</label>
            <input
              type="number"
              id="latitude"
              step="0.01"
              required
              placeholder="例如：31.35"
            />
          </div>
          <div class="form-group">
            <label for="longitude">经度 (Longitude)</label>
            <input
              type="number"
              id="longitude"
              step="0.01"
              required
              placeholder="例如：121.43"
            />
          </div>
          <div class="form-group">
            <label for="date">日期 (Date)</label>
            <input type="date" id="date" required />
          </div>
          <button type="submit">查询并可视化</button>
        </form>
        <div id="result"></div>
      </div>
      <div class="visualization-panel">
        <canvas id="threeCanvas"></canvas>
        <div id="info"></div>
      </div>
    </div>

    <script type="module">
      import * as THREE from "three";
      import { OrbitControls } from "three/addons/controls/OrbitControls.js";
      import {
        CSS2DRenderer,
        CSS2DObject,
      } from "three/addons/renderers/CSS2DRenderer.js";

      let scene, camera, renderer, labelRenderer, controls;
      let celestialObjects = [];
      let labels = [];

      function initThree() {
        scene = new THREE.Scene();
        scene.background = new THREE.Color(0x000000);
        camera = new THREE.PerspectiveCamera(
          75,
          window.innerWidth / window.innerHeight,
          0.1,
          1000
        );
        renderer = new THREE.WebGLRenderer({
          canvas: document.getElementById("threeCanvas"),
          antialias: true,
        });
        renderer.setSize(window.innerWidth, window.innerHeight);

        // 初始化CSS2D渲染器
        labelRenderer = new CSS2DRenderer();
        labelRenderer.setSize(window.innerWidth, window.innerHeight);
        labelRenderer.domElement.style.position = "absolute";
        labelRenderer.domElement.style.top = "0";
        labelRenderer.domElement.style.pointerEvents = "none";
        document
          .querySelector(".visualization-panel")
          .appendChild(labelRenderer.domElement);

        // 基础天球
        const celestialSphere = new THREE.Mesh(
          new THREE.SphereGeometry(2, 30, 30),
          new THREE.MeshBasicMaterial({
            wireframe: true,
            transparent: true,
            opacity: 0.1,
          })
        );
        scene.add(celestialSphere);

        // 赤道平面
        const equatorialPlane = new THREE.Mesh(
          new THREE.CircleGeometry(2, 30),
          new THREE.MeshBasicMaterial({
            color: 0x4169e1,
            transparent: true,
            opacity: 0.2,
            side: THREE.DoubleSide,
          })
        );
        equatorialPlane.rotation.x = Math.PI / 2;
        scene.add(equatorialPlane);

        // 赤道圆圈
        const equatorLine = new THREE.Mesh(
          new THREE.TorusGeometry(2, 0.003, 16, 100),
          new THREE.MeshBasicMaterial({ color: 0xffffff })
        );
        equatorLine.rotation.x = Math.PI / 2;
        scene.add(equatorLine);

        // 坐标轴
        const axesHelper = new THREE.AxesHelper(2.4);
        scene.add(axesHelper);

        // 方位点和标签
        const orientationLabels = [
          "东",
          "东北",
          "北",
          "西北",
          "西",
          "西南",
          "南",
          "东南",
        ];
        for (let i = 0; i < 8; i++) {
          const angle = (i * Math.PI * 2) / 8;
          const x = 2 * Math.cos(angle);
          const z = 2 * Math.sin(angle);
          const y = 0;

          const point = new THREE.Mesh(
            new THREE.SphereGeometry(0.02),
            new THREE.MeshBasicMaterial({ color: 0x00ffff })
          );
          point.position.set(x, y, z);
          scene.add(point);

          // 创建标签
          const labelDiv = document.createElement("div");
          labelDiv.className = "orientation-label";
          labelDiv.textContent = orientationLabels[i];
          labelDiv.style.color = "#ffffff";
          labelDiv.style.fontSize = "14px";
          labelDiv.style.fontWeight = "bold";
          labelDiv.style.textShadow = "0 0 3px rgba(0,0,0,0.8)";
          const label = new CSS2DObject(labelDiv);
          label.position.set(x * 1.1, y, z * 1.1);
          scene.add(label);
          labels.push(label);
        }

        // 初始化控制器
        controls = new OrbitControls(camera, renderer.domElement);
        camera.position.set(4, 4, 4);
        controls.update();
      }

      function updateVisualization(data) {
        // 清除旧对象
        celestialObjects.forEach((obj) => scene.remove(obj));
        celestialObjects = [];

        // 清除旧的天极标签
        labels.forEach((label) => scene.remove(label));
        labels = [];

        // 重新添加方位点和标签
        const orientationLabels = [
          "东",
          "东北",
          "北",
          "西北",
          "西",
          "西南",
          "南",
          "东南",
        ];
        for (let i = 0; i < 8; i++) {
          const angle = (i * Math.PI * 2) / 8;
          const x = 2 * Math.cos(angle);
          const z = 2 * Math.sin(angle);
          const y = 0;

          const point = new THREE.Mesh(
            new THREE.SphereGeometry(0.02),
            new THREE.MeshBasicMaterial({ color: 0x00ffff })
          );
          point.position.set(x, y, z);
          scene.add(point);
          celestialObjects.push(point);

          // 创建标签
          const labelDiv = document.createElement("div");
          labelDiv.className = "orientation-label";
          labelDiv.textContent = orientationLabels[i];
          labelDiv.style.color = "#ffffff";
          labelDiv.style.fontSize = "14px";
          labelDiv.style.fontWeight = "bold";
          labelDiv.style.textShadow = "0 0 3px rgba(0,0,0,0.8)";
          const label = new CSS2DObject(labelDiv);
          label.position.set(x * 1.1, y, z * 1.1);
          scene.add(label);
          labels.push(label);
        }

        const sunDeclination = parseFloat(
          data.sun_declination.replace("°", "")
        );
        const daylightDuration = data.daylight_duration.split(":").map(Number);
        const Ts = daylightDuration[0] + daylightDuration[1] / 60;

        // 创建太阳轨迹
        const points = [];
        const timePoints = 86400;
        const radius = 2;
        const latitude = parseFloat(document.getElementById("latitude").value);
        const delta = (sunDeclination * Math.PI) / 180;

        // 更新赤纬角显示
        document.getElementById("result").innerHTML = `
                <p>日出时间: ${data.sunrise}</p>
                <p>日落时间: ${data.sunset}</p>
                <p>日照时长: ${data.daylight_duration}</p>
                <p>太阳赤纬角: ${data.sun_declination}</p>
            `;

        // 生成太阳轨迹点
        for (let i = 0; i < timePoints; i++) {
          const t = (i / (timePoints - 1)) * Math.PI * 2;
          const d = radius * Math.sin(delta); // 纬圈的垂直偏移量
          const circleRadius = Math.sqrt(radius * radius - d * d); // 计算纬圈半径
          const x = circleRadius * Math.cos(t);
          const y = circleRadius * Math.sin(t);
          const z = d;

          // 计算旋转矩阵
          const zAxis = new THREE.Vector3(0, 0, 1); // 初始纬圈法向量
          const northPoleDir = new THREE.Vector3(
            0,
            Math.sin((latitude * Math.PI) / 180),
            Math.cos((latitude * Math.PI) / 180)
          ).normalize();

          // 计算旋转轴（叉积）
          const rotationAxis = new THREE.Vector3();
          rotationAxis.crossVectors(zAxis, northPoleDir).normalize();

          // 计算旋转角度（点积）
          const rotationAngle = Math.acos(zAxis.dot(northPoleDir));

          // 创建旋转矩阵
          const rotationMatrix = new THREE.Matrix4();
          rotationMatrix.makeRotationAxis(rotationAxis, rotationAngle);

          // 应用旋转
          const point = new THREE.Vector3(x, y, z);
          point.applyMatrix4(rotationMatrix);
          points.push(point);
        }

        // 创建太阳轨迹管道
        const curve = new THREE.CatmullRomCurve3(points);
        const sunPathGeometry = new THREE.TubeGeometry(
          curve,
          50,
          0.01,
          20,
          false
        );
        const sunPathMaterial = new THREE.MeshBasicMaterial({
          color: 0xffff00,
        });
        const sunPath = new THREE.Mesh(sunPathGeometry, sunPathMaterial);
        scene.add(sunPath);
        celestialObjects.push(sunPath);

        // 添加天极点和天轴
        const latitudeRad = (latitude * Math.PI) / 180;
        const northPole = new THREE.Vector3(
          0,
          Math.sin(latitudeRad) * radius * 1.2,
          Math.cos(latitudeRad) * radius * 1.2
        );
        const southPole = northPole.clone().multiplyScalar(-1);

        // 创建天极点标记
        const poleGeometry = new THREE.SphereGeometry(0.03);
        const poleMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });

        // 北天极
        const northPoleMark = new THREE.Mesh(poleGeometry, poleMaterial);
        northPoleMark.position.copy(northPole);
        scene.add(northPoleMark);
        celestialObjects.push(northPoleMark);

        // 南天极
        const southPoleMark = new THREE.Mesh(poleGeometry, poleMaterial);
        southPoleMark.position.copy(southPole);
        scene.add(southPoleMark);
        celestialObjects.push(southPoleMark);

        // 天轴
        const axisGeometry = new THREE.BufferGeometry().setFromPoints([
          northPole,
          southPole,
        ]);
        const axisMaterial = new THREE.LineDashedMaterial({
          color: 0xff0000,
          dashSize: 0.2,
          gapSize: 0.05,
        });
        const celestialAxis = new THREE.Line(axisGeometry, axisMaterial);
        celestialAxis.computeLineDistances();
        scene.add(celestialAxis);
        celestialObjects.push(celestialAxis);

        // 添加天极点标签
        const northPoleDiv = document.createElement("div");
        northPoleDiv.className = "orientation-label";
        northPoleDiv.textContent = "北天极";
        northPoleDiv.style.color = "#ffffff";
        northPoleDiv.style.fontSize = "14px";
        northPoleDiv.style.fontWeight = "bold";
        northPoleDiv.style.textShadow = "0 0 3px rgba(0,0,0,0.8)";
        const northPoleLabel = new CSS2DObject(northPoleDiv);
        northPoleLabel.position.copy(northPole);
        scene.add(northPoleLabel);
        labels.push(northPoleLabel);

        const southPoleDiv = document.createElement("div");
        southPoleDiv.className = "orientation-label";
        southPoleDiv.textContent = "南天极";
        southPoleDiv.style.color = "#ffffff";
        southPoleDiv.style.fontSize = "14px";
        southPoleDiv.style.fontWeight = "bold";
        southPoleDiv.style.textShadow = "0 0 3px rgba(0,0,0,0.8)";
        const southPoleLabel = new CSS2DObject(southPoleDiv);
        southPoleLabel.position.copy(southPole);
        scene.add(southPoleLabel);
        labels.push(southPoleLabel);
      }

      function animate() {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
        labelRenderer.render(scene, camera);
      }

      function onWindowResize() {
        const container = document.querySelector(".visualization-panel");
        camera.aspect = container.clientWidth / container.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(container.clientWidth, container.clientHeight);
        labelRenderer.setSize(container.clientWidth, container.clientHeight);
      }

      // 初始化场景
      initThree();
      window.addEventListener("resize", onWindowResize, false);
      onWindowResize();
      animate();

      // 设置默认值并自动提交表单
      window.addEventListener("load", function () {
        // 检查localStorage中是否有保存的位置信息
        if (
          localStorage.getItem("locationName") &&
          localStorage.getItem("coordinates")
        ) {
          const coordsText = localStorage.getItem("coordinates").trim();

          let longitude = 121.4737; // 默认上海经度
          let latitude = 31.2304; // 默认上海纬度

          try {
            // 尝试解析经纬度格式
            let lonMatch, latMatch;

            // 格式1: 121.4737°E 31.2304°N
            lonMatch = coordsText.match(/([-+]?\d+(\.\d+)?)°?\s*([EW])/i);
            latMatch = coordsText.match(/([-+]?\d+(\.\d+)?)°?\s*([NS])/i);

            // 格式2: 121°28'25"E 31°13'49"N
            if (!lonMatch)
              lonMatch = coordsText.match(/(\d+)°(\d+)'(\d+)"?\s*([EW])/i);
            if (!latMatch)
              latMatch = coordsText.match(/(\d+)°(\d+)'(\d+)"?\s*([NS])/i);

            // 格式3: 121.4737, 31.2304
            if (!lonMatch && !latMatch) {
              const decimalMatch = coordsText.match(
                /([-+]?\d+(\.\d+)?),\s*([-+]?\d+(\.\d+)?)/
              );
              if (decimalMatch) {
                longitude = parseFloat(decimalMatch[1]);
                latitude = parseFloat(decimalMatch[3]);
              }
            } else {
              // 解析经度
              if (lonMatch.length === 4) {
                longitude = parseFloat(lonMatch[1]);
                if (lonMatch[3].toUpperCase() === "W") longitude = -longitude;
              } else if (lonMatch.length === 5) {
                longitude =
                  parseInt(lonMatch[1]) +
                  parseInt(lonMatch[2]) / 60 +
                  parseInt(lonMatch[3]) / 3600;
                if (lonMatch[4].toUpperCase() === "W") longitude = -longitude;
              }

              // 解析纬度
              if (latMatch.length === 4) {
                latitude = parseFloat(latMatch[1]);
                if (latMatch[3].toUpperCase() === "S") latitude = -latitude;
              } else if (latMatch.length === 5) {
                latitude =
                  parseInt(latMatch[1]) +
                  parseInt(latMatch[2]) / 60 +
                  parseInt(latMatch[3]) / 3600;
                if (latMatch[4].toUpperCase() === "S") latitude = -latitude;
              }
            }
          } catch (e) {
            console.error("解析坐标时出错:", e);
          }

          // 设置表单值
          document.getElementById("latitude").value = latitude.toFixed(2);
          document.getElementById("longitude").value = longitude.toFixed(2);
        } else {
          // 如果没有保存的位置，使用默认值（上海）
          document.getElementById("latitude").value = "31.2304";
          document.getElementById("longitude").value = "121.4737";
        }

        // 设置当前日期
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        document.getElementById("date").value = `${year}-${month}-${day}`;

        // 自动提交表单
        document.getElementById("astroForm").dispatchEvent(new Event("submit"));
      });

      // 表单提交处理
      document
        .getElementById("astroForm")
        .addEventListener("submit", async function (e) {
          e.preventDefault();
          const latitude = document.getElementById("latitude").value;
          const longitude = document.getElementById("longitude").value;
          const date = document.getElementById("date").value;

          const minLatitude = 3.5;
          const maxLatitude = 53.4;
          const minLongitude = 73.3;
          const maxLongitude = 135.1;

          // 判断输入的经纬度是否在中国范围内
          if (
            latitude < minLatitude ||
            latitude > maxLatitude ||
            longitude < minLongitude ||
            longitude > maxLongitude
          ) {
            document.getElementById("result").innerHTML =
              "请输入中国范围内的经纬度";
            return; // 如果不在范围内，停止后续操作
          }

          try {
            const response = await fetch("/api/calculate", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ latitude, longitude, date }),
            });

            const data = await response.json();
            updateVisualization(data);
          } catch (error) {
            console.error("Error:", error);
            document.getElementById("result").innerHTML =
              "获取数据时出错，请重试";
          }
        });
    </script>
    <div
      style="position: fixed; left: 10px; top: 50%; transform: translateY(-50%)"
    >
      <button class="button" onclick="window.location.href='十二宫图.html'">
        <img src={{ url_for('static', filename='素材/left.png' ) }} alt="moon"
        />
      </button>
    </div>
    <div class="footer">
      <button
        class="calendar-btn"
        onclick="window.location.href='newcalendar.html'"
      >
        <img
          src="{{ url_for('static', filename='素材/日历浅色.png') }}"
          alt="calendar"
        />
      </button>
      <button class="moon-btn" onclick="window.location.href='十二宫图.html'">
        <img
          src="{{ url_for('static', filename='素材/可视化深色.png') }}"
          alt="moon"
        />
      </button>
      <button class="data-btn" onclick="window.location.href='newdata.html'">
        <img
          src="{{ url_for('static', filename='素材/知识浅色.png') }}"
          alt="data"
        />
      </button>
      <button class="index-btn" onclick="window.location.href='newai.html'">
        <img
          src="{{ url_for('static', filename='素材/大模型.png') }}"
          alt="index"
        />
      </button>
    </div>
  </body>
</html>
